import {ref} from 'vue'

export interface ImageErrorOptions {
    maxRetries?: number
    retryDelay?: number
    fallbackImage?: string
    onError?: (error: Event, retries: number) => void
    onRetry?: (retries: number) => void
    onSuccess?: () => void
}

export function useImageError(options: ImageErrorOptions = {}) {
    const {
        maxRetries = 3,
        retryDelay = 1000,
        fallbackImage = '/placeholder-error.svg',
        onError,
        onRetry,
        onSuccess
    } = options

    const retryCount = ref(0)
    const currentSrc = ref('')
    const isError = ref(false)
    const isLoading = ref(true)

    const reset = (initialSrc: string) => {
        retryCount.value = 0
        currentSrc.value = initialSrc
        isError.value = false
        isLoading.value = true
    }

    const handleError = (event: Event, originalSrc: string) => {
        const img = event.target as HTMLImageElement

        onError?.(event, retryCount.value)

        if (retryCount.value < maxRetries) {
            retryCount.value++
            onRetry?.(retryCount.value)

            setTimeout(() => {
                const separator = originalSrc.includes('?') ? '&' : '?'
                currentSrc.value = `${originalSrc}${separator}retry=${retryCount.value}&t=${Date.now()}`
                img.src = currentSrc.value
            }, retryDelay * retryCount.value)
        } else {
            isError.value = true
            isLoading.value = false
            currentSrc.value = fallbackImage
            img.src = fallbackImage
            img.alt = '图片加载失败'
        }
    }

    const handleLoad = () => {
        isLoading.value = false
        isError.value = false
        if (retryCount.value > 0) {
            onSuccess?.()
        }
    }

    const retry = (src: string) => {
        if (retryCount.value < maxRetries) {
            retryCount.value++
            const separator = src.includes('?') ? '&' : '?'
            currentSrc.value = `${src}${separator}retry=${retryCount.value}&t=${Date.now()}`
        }
    }

    return {
        retryCount,
        currentSrc,
        isError,
        isLoading,
        handleError,
        handleLoad,
        reset,
        retry
    }
}
